package com.lvmama.rhino.job;

import com.alibaba.fastjson.JSONArray;
import com.lvmama.rhino.entity.SendMailVO;
import com.lvmama.rhino.mapper.HotelDataMapper;
import com.lvmama.rhino.pojo.ProductDetail;
import com.lvmama.rhino.utils.DateUtil;
import com.lvmama.rhino.utils.ExportExcelUtils;
import com.lvmama.rhino.utils.SendMailUtil;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.lang.reflect.Field;
import java.util.*;

/**
 * @Description: 酒店数据提供
 * @Author: sunpengpeng
 * @Date: Create in 2018/7/4 10:24
 * @Modified By:
 */
public class HotelDataJob extends BaseQuartzJobBean {

    public static Logger log = Logger.getLogger(HotelDataJob.class);

    @Autowired
    private HotelDataMapper hotelDataMapper;

    @Value("${hotelData.export.path}")
    private String path;

    @Value("${hotelData.email.flag}")
    private String flag;

    @Value("${hotelData.email.toUser}")
    private String toUser;

    @Value("${hotelData.email.bccUser}")
    private String bccUser;

    @Override
    public void invoke(JobExecutionContext context) {
        log.info("invoke HotelDataJob start.");
        if(!Boolean.valueOf(flag)){
            return;
        }
        ProductDetail productDetail = new ProductDetail();
        productDetail.setCategoryId("1");
        productDetail.setStartDate(DateUtil.getDateBeforeMonth(new Date(),-1));
        productDetail.setEndDate(new Date());
        List<ProductDetail> productDetailList = hotelDataMapper.findHotelList(productDetail);
        List<ProductDetail> productList = new ArrayList<>();

        if (productDetailList != null && productDetailList.size() > 0) {
            Map<Object, ProductDetail> productDetailMap = new HashMap<>();

            for (ProductDetail pro : productDetailList) {
                JSONArray jsonData = null;
                try {
                    jsonData = JSONArray.parseArray(pro.getProductJson());
                } catch (Exception e) {
                    System.out.println(pro.getProductJson());
                    continue;
                }
                for (int i = 0; i < jsonData.size(); i++) {
                    JSONArray jo = (JSONArray) jsonData.get(i);
                    ProductDetail productDetailVo = new ProductDetail();
                    productDetailVo.setProductId(jo.get(0).toString());
                    productDetailVo.setProductName(jo.get(1).toString());
                    productDetailVo.setAmount(Integer.parseInt(jo.get(2).toString()));
                    if (productDetailMap.containsKey(jo.get(0))) {
                        productDetailMap.get(jo.get(0)).setAmount(productDetailMap.get(jo.get(0)).getAmount() + Integer.parseInt(jo.get(2).toString()));
                    } else {
                        productDetailMap.put(jo.get(0), productDetailVo);
                    }
                }

            }
            for (Map.Entry<Object, ProductDetail> entry : productDetailMap.entrySet()) {
                productList.add(entry.getValue());
            }
        }
        Collections.sort(productList, new Comparator<ProductDetail>() {
            @Override
            public int compare(ProductDetail o1, ProductDetail o2) {
                return o2.getAmount() - o1.getAmount();
            }
        });
        ExportExcelUtils<ProductDetail> exportExcelUtils = new ExportExcelUtils<ProductDetail>();
        String startTime = DateUtil.formatDate(DateUtil.getDateBeforeMonth(new Date(),-1),"yyyyMMdd");
        String endTime = DateUtil.formatDate(new Date(),"MMdd");
        String fileName = "酒店列表_"+startTime+"-"+endTime;
        String[] headers = new String[]{"酒店ID", "酒店名称", "访问量"};
        Field[] fields = getFields(headers);
        exportExcelUtils.getHSSFSheet(fileName, headers, fields, productList, "yyyy-MM-dd");
        File file = new File(path + fileName + ".xls");
        try {
            if (!file.exists()) {
                file.createNewFile();
                file.setWritable(true, false);
            }
            exportExcelUtils.writeToOutput(new FileOutputStream(file));
            SendMailVO sendMailVO = new SendMailVO();
            sendMailVO.setToMail(toUser);
            sendMailVO.setBccMail(bccUser);
            sendMailVO.setSubject(fileName);
            sendMailVO.setFilename(fileName);
            String content="<html>\n" +
                            "<body>\n" +
                            "<h3>Hi</h3>\n" +
                            "<h3>   附件为最近一个月酒店访问列表（按访问量降序），日期为"+startTime+"-"+endTime +"每周发一次!谢谢</h3>\n" +
                            "</body>\n" +
                            "</html>";
            sendMailVO.setContent(content);
            sendMailVO.setInputStream(new FileInputStream(file));
            SendMailUtil.sendMail(sendMailVO);
        } catch (Exception ex) {
            log.error("表格异常");
        }

        log.info("invoke HotelDataJob end.");
    }

    /**
     * 根据每列字段名称创建需要导出字段的数组
     *
     * @param headers
     * @return
     */
    public Field[] getFields(String[] headers) {
        Field[] fields = new Field[headers.length];
        ProductDetail t = new ProductDetail();
        try {
            for (int i = 0; i < headers.length; i++) {
                if (headers[i].equals("酒店ID")) {
                    fields[i] = t.getClass().getDeclaredField("productId");
                } else if (headers[i].equals("酒店名称")) {
                    fields[i] = t.getClass().getDeclaredField("productName");
                } else if (headers[i].equals("访问量")) {
                    fields[i] = t.getClass().getDeclaredField("amount");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fields;
    }

    public String exportExcel(List<ProductDetail> list, String fileName) throws Exception {
        WritableWorkbook wwb = null;
        File file = new File(path + fileName + ".xls");
        if (!file.exists()) {
            file.createNewFile();
        }
        wwb = Workbook.createWorkbook(file);

        WritableSheet ws = wwb.createSheet("酒店名单", 0);

        ws.addCell(new Label(0, 0, "酒店ID"));
        ws.addCell(new Label(1, 0, "酒店名称"));
        ws.addCell(new Label(2, 0, "访问量"));

        for (int i = 0; i < list.size(); i++) {
            ws.addCell(new Label(0, i + 1, list.get(i).getProductId()));
            ws.addCell(new Label(1, i + 1, list.get(i).getProductName()));
            ws.addCell(new Label(2, i + 1, list.get(i).getAmount().toString()));
        }
        wwb.write();
        try {
            wwb.close();
        } catch (WriteException e) {
            e.printStackTrace();
        }
        return path + fileName + ".xls";
    }
}
